package com.example.smssender;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import java.util.ArrayList;
import java.util.List;

/**
 * 发送进度详情对话框（BottomSheet）
 */
public class SendingProgressBottomSheetDialog extends BottomSheetDialogFragment {
    
    private static final String TAG = "SendingProgressBS";
    private static final String ARG_STATUS_LIST = "status_list";
    
    private RecyclerView rvProgress;
    private TextView tvProgressSummary;
    private ImageButton btnClose;
    private SendingProgressAdapter adapter;
    private List<SendingStatus> statusList;
    
    public static SendingProgressBottomSheetDialog newInstance(List<SendingStatus> statusList) {
        SendingProgressBottomSheetDialog dialog = new SendingProgressBottomSheetDialog();
        Bundle args = new Bundle();
        // 将状态列表序列化传递（由于SendingStatus实现了Serializable）
        args.putSerializable(ARG_STATUS_LIST, (java.io.Serializable) new ArrayList<>(statusList));
        dialog.setArguments(args);
        return dialog;
    }
    
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateDialog: 创建对话框");
        try {
            Context context = requireContext();
            BottomSheetDialog dialog = new BottomSheetDialog(context, R.style.Theme_SMSSender_BottomSheet);
            return dialog;
        } catch (Exception e) {
            Log.e(TAG, "onCreateDialog: 创建对话框失败", e);
            Context context = getContext();
            if (context != null) {
                return new BottomSheetDialog(context);
            }
            return super.onCreateDialog(savedInstanceState);
        }
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bottom_sheet_sending_progress, container, false);
        
        rvProgress = view.findViewById(R.id.rvProgress);
        tvProgressSummary = view.findViewById(R.id.tvProgressSummary);
        btnClose = view.findViewById(R.id.btnClose);
        
        // 设置关闭按钮点击事件
        if (btnClose != null) {
            btnClose.setOnClickListener(v -> {
                if (getDialog() != null) {
                    dismiss();
                }
            });
        }
        
        // 从参数中获取状态列表
        if (getArguments() != null) {
            @SuppressWarnings("unchecked")
            ArrayList<SendingStatus> list = (ArrayList<SendingStatus>) getArguments().getSerializable(ARG_STATUS_LIST);
            statusList = list != null ? list : new ArrayList<>();
        } else {
            statusList = new ArrayList<>();
        }
        
        // 初始化适配器
        adapter = new SendingProgressAdapter(statusList);
        rvProgress.setLayoutManager(new LinearLayoutManager(getContext()));
        rvProgress.setAdapter(adapter);
        
        // 更新摘要信息
        updateSummary();
        
        return view;
    }
    
    /**
     * 更新状态列表（用于实时更新）
     */
    public void updateStatusList(List<SendingStatus> newStatusList) {
        if (adapter != null && newStatusList != null) {
            statusList = newStatusList; // 更新本地状态列表
            adapter.updateStatusList(newStatusList);
            updateSummary();
        }
    }
    
    /**
     * 更新摘要信息
     */
    private void updateSummary() {
        if (tvProgressSummary == null || statusList == null) {
            return;
        }
        
        int total = statusList.size();
        int success = 0;
        int failed = 0;
        int sending = 0;
        int pending = 0;
        
        for (SendingStatus status : statusList) {
            switch (status.getStatus()) {
                case SendingStatus.STATUS_SUCCESS:
                    success++;
                    break;
                case SendingStatus.STATUS_FAILED:
                    failed++;
                    break;
                case SendingStatus.STATUS_SENDING:
                    sending++;
                    break;
                case SendingStatus.STATUS_PENDING:
                    pending++;
                    break;
            }
        }
        
        String summary = String.format("总计：%d | 成功：%d | 失败：%d | 发送中：%d | 待发送：%d",
                total, success, failed, sending, pending);
        tvProgressSummary.setText(summary);
    }
}

